package com.ssy.lingxi.search.serviceImpl;

import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.search.api.model.request.CommodityCollectBatchRequest;
import com.ssy.lingxi.search.api.model.request.CommodityCollectRequest;
import com.ssy.lingxi.search.api.model.response.CollectResponse;
import com.ssy.lingxi.search.entity.Commodity;
import com.ssy.lingxi.search.entity.CommodityCollect;
import com.ssy.lingxi.search.repository.CommodityCollectRepository;
import com.ssy.lingxi.search.repository.CommodityRepository;
import com.ssy.lingxi.search.service.ICommodityCollectService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品收藏实现类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class CommodityCollectServiceImpl implements ICommodityCollectService {

    @Resource
    private CommodityCollectRepository commodityCollectRepository;

    @Resource
    private CommodityRepository commodityRepository;

    /**
     * 查询该商品是否已经收藏
     * @param commodityId 商品id
     */
    @Override
    public CollectResponse getCommodityCollectByCommodityId(Long commodityId, UserLoginCacheDTO sysUser, Long shopId) {
        CollectResponse collectResponse = new CollectResponse();
        Boolean exists = commodityCollectRepository.existsByCommodityIdAndMemberIdAndMemberRoleIdAndUserIdAndShopId(commodityId, sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId);
        Integer count = commodityCollectRepository.countByCommodityIdAndShopId(commodityId, shopId);
        collectResponse.setIsCollect(exists);
        collectResponse.setCount(count);
        return collectResponse;
    }

//    /**
//     * 查询商品收藏列表
//     */
//    @Override
//    public List<CommodityCollect> getCommodityCollectList(UserLoginCacheDTO sysUser){
//        return commodityCollectRepository.findByMemberIdAndMemberRoleIdAndUserId(sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId());
//    }

    /**
     * 查询商品收藏列表
     * @param pageVO
     */
    @Override
    public Page<CommodityCollect> getCommodityCollectList(UserLoginCacheDTO sysUser, Long shopId, PageVO pageVO){
        Sort sort = Sort.by("createTime").descending();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), sort);
        return commodityCollectRepository.findByMemberIdAndMemberRoleIdAndUserIdAndShopId(sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId, page);
    }

    /**
     * 查询商品收藏列表
     * @param pageVO
     */
    @Override
    public Page<CommodityCollect> getCommodityCollectList(UserLoginCacheDTO sysUser, PageVO pageVO){
        Sort sort = Sort.by("createTime").descending();
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), sort);
        return commodityCollectRepository.findByMemberIdAndMemberRoleIdAndUserId(sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), page);
    }

    /**
     * 添加商品收藏
     * @param commodityCollectRequest
     * @return
     */
    @Override
    public Long saveCommodityCollect(UserLoginCacheDTO sysUser, Long shopId, CommodityCollectRequest commodityCollectRequest){
        Long commodityId = commodityCollectRequest.getCommodityId();
        //检查该商品是否存在
        if(commodityId != null && commodityId > 0){
            //验证数据库中是否存在该数据
            Commodity commodity = commodityRepository.findById(commodityId).orElse(null);
            if(commodity == null){
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
            }
        }else{
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }
        //检查是否已经收藏过
        Boolean exists = commodityCollectRepository.existsByCommodityIdAndMemberIdAndMemberRoleIdAndUserIdAndShopId(commodityId, sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId);
        if(exists){
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_COLLECT_EXIST);
        }
        //数据库持久化对象
        CommodityCollect commodityCollect = new CommodityCollect();
        commodityCollect.setCommodityId(commodityId);
        commodityCollect.setShopId(shopId);
        commodityCollect.setMemberId(sysUser.getMemberId());
        commodityCollect.setMemberName(sysUser.getCompany());
        commodityCollect.setMemberRoleId(sysUser.getMemberRoleId());
        commodityCollect.setMemberRoleName(sysUser.getMemberRoleName());
        commodityCollect.setUserId(sysUser.getUserId());
        commodityCollect.setUserName(sysUser.getUserName());
        commodityCollectRepository.saveAndFlush(commodityCollect);
        return commodityCollect.getId();
    }

    /**
     * 批量添加商品收藏
     * @param simpleCommodityIdListRequest
     * @return
     */
    @Override
    public Boolean saveBatchCommodityCollect(UserLoginCacheDTO sysUser, Long shopId, CommodityCollectBatchRequest simpleCommodityIdListRequest) {
        List<Long> commodityIdList = simpleCommodityIdListRequest.getCommodityIdList();
        List<CommodityCollect> resultList = commodityIdList.stream().map(commodityId -> {
            //检查该商品是否存在
            if (commodityId != null && commodityId > 0) {
                //验证数据库中是否存在该数据
                Commodity commodity = commodityRepository.findById(commodityId).orElse(null);
                if (commodity == null) {
                    throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
                }
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
            }
            //检查是否已经收藏过
            Boolean exists = commodityCollectRepository.existsByCommodityIdAndMemberIdAndMemberRoleIdAndUserIdAndShopId(commodityId, sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId);
            if(!exists){
                //数据库持久化对象
                CommodityCollect commodityCollect = new CommodityCollect();
                commodityCollect.setCommodityId(commodityId);
                commodityCollect.setShopId(shopId);
                commodityCollect.setMemberId(sysUser.getMemberId());
                commodityCollect.setMemberName(sysUser.getCompany());
                commodityCollect.setMemberRoleId(sysUser.getMemberRoleId());
                commodityCollect.setMemberRoleName(sysUser.getMemberRoleName());
                commodityCollect.setUserId(sysUser.getUserId());
                commodityCollect.setUserName(sysUser.getUserName());
                return commodityCollect;
            }else{
                return null;
            }
        }).filter(Objects::nonNull).collect(Collectors.toList());
        if(resultList.size() > 0){
            commodityCollectRepository.saveAll(resultList);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除商品收藏
     * @param commodityCollectRequest
     * @return
     */
    @Override
    public String deleteCommodityCollect(UserLoginCacheDTO sysUser, Long shopId, CommodityCollectRequest commodityCollectRequest) {
        Long commodityId = commodityCollectRequest.getCommodityId();
        //验证数据库中是否存在该数据
        List<CommodityCollect> commodityCollectList = commodityCollectRepository.findByCommodityIdAndMemberIdAndMemberRoleIdAndUserIdAndShopId(commodityId, sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId);
        if(commodityCollectList != null && !commodityCollectList.isEmpty()){
            commodityCollectRepository.deleteAll(commodityCollectList);
            return ResponseCode.SUCCESS.getMessage();
        }else{
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_COLLECT_NOT_EXIST);
        }
    }

    /**
     * 删除商品收藏通过id
     * @param id
     * @return
     */
    @Override
    public String deleteCommodityCollectById(UserLoginCacheDTO sysUser, Long id) {
        CommodityCollect commodityCollect = commodityCollectRepository.findById(id).orElse(null);
        if(commodityCollect != null){
            Long memberId = commodityCollect.getMemberId();
            Long memberRoleId = commodityCollect.getMemberRoleId();
            Long userId = commodityCollect.getUserId();
            if(memberId.equals(sysUser.getMemberId()) && memberRoleId.equals(sysUser.getMemberRoleId()) && userId.equals(sysUser.getUserId())){
                commodityCollectRepository.deleteById(id);
                return ResponseCode.SUCCESS.getMessage();
            }
        }
        throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_COLLECT_NOT_EXIST);
    }

}

